import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { API_BASE_URL } from '@/utils/constants';
import { CreateRoomResponse, Room, ApiError } from '@/types';

/**
 * API 客户端类
 */
class ApiClient {
  private client: AxiosInstance;

  constructor() {
    this.client = axios.create({
      baseURL: API_BASE_URL,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json',
      },
    });

    // 请求拦截器
    this.client.interceptors.request.use(
      (config) => {
        // 可以在这里添加认证 token
        // const token = localStorage.getItem('token');
        // if (token) {
        //   config.headers.Authorization = `Bearer ${token}`;
        // }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // 响应拦截器
    this.client.interceptors.response.use(
      (response: AxiosResponse) => {
        return response;
      },
      (error) => {
        const apiError: ApiError = {
          message: error.response?.data?.message || error.message || '网络错误',
          statusCode: error.response?.status || 0,
          error: error.response?.data?.error,
        };
        return Promise.reject(apiError);
      }
    );
  }

  /**
   * 创建房间
   */
  async createRoom(userId?: string): Promise<CreateRoomResponse> {
    const response = await this.client.post<CreateRoomResponse>('/api/rooms', {
      userId,
    });
    return response.data;
  }

  /**
   * 获取房间信息
   */
  async getRoomInfo(roomId: string): Promise<Room> {
    const response = await this.client.get<Room>(`/api/rooms/${roomId}`);
    return response.data;
  }

  /**
   * 检查房间是否存在
   */
  async checkRoomExists(roomId: string): Promise<boolean> {
    try {
      await this.getRoomInfo(roomId);
      return true;
    } catch (error) {
      const apiError = error as ApiError;
      if (apiError.statusCode === 404) {
        return false;
      }
      throw error;
    }
  }

  /**
   * 获取房间参与者列表
   */
  async getRoomParticipants(roomId: string): Promise<string[]> {
    const response = await this.client.get<string[]>(`/api/rooms/${roomId}/participants`);
    return response.data;
  }

  /**
   * 健康检查
   */
  async healthCheck(): Promise<{ status: string; timestamp: string }> {
    const response = await this.client.get('/api/health');
    return response.data;
  }

  /**
   * 获取服务器统计信息
   */
  async getServerStats(): Promise<{
    activeRooms: number;
    totalConnections: number;
    uptime: number;
  }> {
    const response = await this.client.get('/api/stats');
    return response.data;
  }
}

// 创建单例实例
export const apiClient = new ApiClient();

// 导出具体的 API 方法
export const roomApi = {
  /**
   * 创建新房间
   */
  create: (userId?: string) => apiClient.createRoom(userId),

  /**
   * 获取房间详情
   */
  getInfo: (roomId: string) => apiClient.getRoomInfo(roomId),

  /**
   * 检查房间是否存在
   */
  exists: (roomId: string) => apiClient.checkRoomExists(roomId),

  /**
   * 获取房间参与者
   */
  getParticipants: (roomId: string) => apiClient.getRoomParticipants(roomId),
};

export const systemApi = {
  /**
   * 健康检查
   */
  health: () => apiClient.healthCheck(),

  /**
   * 获取服务器统计
   */
  stats: () => apiClient.getServerStats(),
};

// 默认导出
export default apiClient;